define(['../../common/common', '../../common/pathCompute', 'ztree', 'text!../../../pages/project/projectUnitAdd.html', 'text!../../../pages/dataBase/materialService.html', '../materialService'], function($, pathfn, ztree, projectUnitAddHtml, materialServiceHtml, materialService) {
	var interface =  pathfn.interface,
		backDataAll = {},
		backDataYcaAll = {}, //点击运材安里面的新增按钮 里面的选择搜索按钮返回的数据
		tableRender = pathfn.tableRender; //表格thead参数
	var projectUnitAddFbfxHtml  =  $(projectUnitAddHtml)[0],
	projectUnitYcaHtml = $(projectUnitAddHtml)[2];
  	projectDw = function(projectId){
  		layui.use([ 'table','form','laypage','layedit', 'element'],function() {			
          	var table = layui.table,
          	form = layui.form,
          	layedit = layui.layedit,
          	laypage = layui.laypage,
          	element = layui.element;
          	
          	var init= function(){
          		ztreeOperatea.ztreeInit();
            	bindEvents();
          	},
          	ztreeOperatea = {
				setting: {
					view: {
			            showLine: false,
			            showIcon: false,
			            selectedMulti: false,//是否允许多选  
			            addDiyDom: function(treeId, treeNode){
							return ztreeOperatea.addDiyDom(treeId, treeNode);
					    }
			        },
			        data: {
			            simpleData: {
			                enable: true
			            },
			            key: {
							name: "code"
						}
			        },
			        check: {  
		                enable: true,  
		                nocheckInherit: false,
		                autoCheckTrigger: true,
		                chkStyle: "radio"
		            },
					async: {
						enable: true,
						url: interface.projectItemInfo,
						otherParam: ["bitProjectId", projectId],
						dataFilter: function(treeId, parentNode, responseData){
							return ztreeOperatea.ajaxDataFilter(treeId, parentNode, responseData);
					    }
					},
					callback: {
						onCheck: function (event, treeId, treeNode) {
						    var treeObj = $.fn.zTree.getZTreeObj("dataTree"), 
        						changedNodes = treeObj.getCheckedNodes(true);
        					if(changedNodes.length){
			                    treeObj.selectNode(changedNodes[0]);
			                    projectMatTabOperate.tableInit(changedNodes[0]);  
        					}
						},
						onAsyncSuccess: function(event, treeId, treeNode, msg) {

							//添加表头
							var unitproject = tableRender.unitproject,
							li_head = '',
							$li = $('<li class="head"></li>');
							for(var i=0;i<unitproject.length;i++){
								li_head+= '<div class="diy">'+ unitproject[i].text+'</div>';
							}
							$li.append('<a>'+li_head+'<div class="diy">操作</div></a>');
					        var rows = $("#dataTree").find('li');					        
					        if (rows.length > 0) {
					            rows.eq(0).before($li)
					        } else {
					            $("#dataTree").append($li);
					            $("#dataTree").append('<li ><div style="text-align: center;line-height: 30px;" >无符合条件数据</div></li>')
					        }
					        ztreeOperatea.ztreeEvents();

					        var treeObj = $.fn.zTree.getZTreeObj("dataTree"),
					        	nodes = treeObj.getNodes();
					        if(!nodes[0] || !nodes[0].children) return;
					        treeObj.selectNode(nodes[0].children[0]); //选中某个节点
					        treeObj.checkNode(nodes[0].children[0], true, true); //选中某个checkbox
					        projectMatTabOperate.tableInit(nodes[0].children[0]);
							//展开ztree
							treeObj.expandAll(true);
					        
						},
						onClick: function(even, treeId, treeNode) {
							var treeNode = treeNode[0] || treeNode,
								treeObj = $.fn.zTree.getZTreeObj("dataTree");
		                    treeObj.checkNode(treeNode, !treeNode.checked, true);
		                    console.log(treeNode) 
		                    projectMatTabOperate.tableInit(treeNode);
						}
					}
				},
				ztreeInit: function() { //加载左侧菜单树
					$.fn.zTree.init($("#dataTree"), this.setting);
				},
				addDiyDom: function(treeId, treeNode){  //ztree渲染成表格
			        var _this = this,spaceWidth = 15;
			        var liObj = $("#" + treeNode.tId),
			        	checkObj = $("#" + treeNode.tId + "_check"),
			        	aObj = $("#" + treeNode.tId + "_a"),
			        	switchObj = $("#" + treeNode.tId + "_switch"),
			        	icoObj = $("#" + treeNode.tId + "_ico"),
			        	spanObj = $("#" + treeNode.tId + "_span");
			        aObj.attr('title', '').attr('class','ztree_aobj');
			        aObj.append('<div class="diy swich"></div>');
			        spanObj.attr('class','ztree-span');
			        var div = $(liObj).find('div').eq(0);
			        div.append(switchObj);
			        div.append(spanObj);
			        var spaceStr = "<span style='height:1px;display: inline-block;width:" + (spaceWidth * treeNode.level) + "px'></span>";
			        switchObj.before(spaceStr);
			        var editStr = [],
			       	unitproject = tableRender.unitproject;
					for(var i=2;i<unitproject.length;i++){
						var name = unitproject[i].name,
						item = treeNode[name];
						editStr.push('<div class="diy">' + (!item && item !== 0 ? '&nbsp;' : item ) + '</div>');
					}
			        editStr.push('<div class="diy ztree_caozuo">' + (treeNode.code == "整个项目" ?  '&nbsp;' : _this.formatHandle(treeNode)) + '</div>');
			        checkObj.wrap('<div class="ztree-checkObj"></div>');
			        aObj.append(editStr).parents('#dataTree').eq(0).width((editStr.length)*145+155+38); //计算表格宽度，添加滚动条

			    },
			    ajaxDataFilter: function(treeId, parentNode, responseData) { // 对ajax返回的数据进行过滤
			    	var child = responseData.children;
				    if (child.length) {
				      for(var i =0; i < child.length; i++) {
				        child[i].code = child[i].code ? child[i].code : child[i].name;
				        child[i].open = !child[i].leaf;
				        child[i].nocheck = !child[i].leaf;
				      }
				    }
				    return child;
				},
			    formatHandle: function(treeNode) {  // 显示操作的按钮
			        var htmlStr = '';
			        htmlStr += '<div class="icon_div"><a class="icon_view" title="查看" data-tid="'+treeNode.tId+'"  href="javascript:;">查看</a></div>';
			        htmlStr += '<div class="icon_div"><a class="icon_edit" title="修改" data-tid="'+treeNode.tId+'" href="javascript:;">修改</a></div>';
			        htmlStr += '<div class="icon_div"><a class="icon_del" title="删除" data-tid="'+treeNode.tId+'" href="javascript:;">删除</a></div>';
			        return htmlStr;
			    },
			    ztreeEvents: function(){
			    	$(document).on('click', '.icon_view' , function(e){
			    		var tid = $(this).data('tid');
			    		var treeObj = $.fn.zTree.getZTreeObj("dataTree"),
			        	node = treeObj.getNodeByTId(tid);
			        	treeObj.selectNode(node);
			    	})
			    	$(document).on('click', '.icon_edit' , function(e){
			    		var tId = $(this).data('tid');
			    		var treeObj = $.fn.zTree.getZTreeObj("dataTree"),
			        	node = treeObj.getNodeByTId(tid);
			    	})
			    	$(document).on('click', '.icon_del' , function(e){
			    		var tid = $(this).data('tid'),
			    		treeObj = $.fn.zTree.getZTreeObj("dataTree"),
			        	node = treeObj.getNodeByTId(tid);
			        	var openObj = {
		                  	content: '确认删除吗？',
		                  	title: "删除",
		                  	success: function(layero, index){			                    
			                },
			                yes: function(){
		                    	$.ajaxRequest({
							    	url: interface.deleteProjectItem,
							    	data:{
										"cmd": "edit",
										"unitProjectId": node.id
									},
							    	successfn: function(data) {
							    		console.log(typeof data)
							    		if(data.success){
							    			treeObj.removeNode(node);
					                    	layer.close(popIndex);
							    		}
							    		
							    	}
								})                    	
		                    }
		                }
		                layerOpenfn(openObj); 
			    	})

			    }
	        },      	
          	projectMatTabOperate = {
				tableInitObj: function(){
              		var obj = {
		              id: 'projectMaterial-table',
		              elem: '#projectMaterial-table', //指定原始表格元素选择器（推荐id选择器）
		              height: '400', //容器高度
		              cols:  [[ //标题栏
		                {field:'no', title: '序号', width:100, sort: true, align:'center'},
		                {field:'code', title: '编码', width:200, sort: true},
		                {field:'name', title: '类别', width:200},
		                {field:'name', title: '名称', width:200},
		                {field:'typeInfo', title: '规格及型号', width:200, edit: 'text'},		                
		                {field:'unit', title: '单位', width:100, align:'center'},
		                {field:'content', title: '含量', width:200, edit: 'text'},
		                {field:'amount', title: '数量', width:200},
		                {field:'noTaxPrice', title: '不含税单价', width:150, align:'center'},
		                {field:'taxPrice', title: '含税单价', width:150, align:'center', edit: 'text'},
		                {field:'singleSumPrice', title: '不含税合价', width:150, align:'center'},
		                {field:'taxSingleSumPrice', title: '含税合价', width:150, align:'center'},
		                {field:'origTaxPrice', title: '原始含量', width:200},
		                {field:'caozuo', fixed: 'right', title: '操作', width:80, align:'center', fixed:'right', toolbar: '#item-barDemo'}
		              ]],
		              url: interface.projectDetailInfo,
		              method: 'get',
		              page: false, //开启分页
		              limit: 10000, //默认采用60
		              loading: true              
		            }
              		return obj;
              	},
              	tableInit: function(obj){
		            var _this = this,
		            defaults = {
		            	where: {
			              	unitProjectId: obj.id,
			              	start: 0,
			              	page: 1
			            },
			            done: function(res, curr, count){
			              	_this.listEdit(_this.tableInitObj()); 
			            }
		            }
		           	$.extend(true, defaults, _this.tableInitObj());  
		            table.render(defaults);
		            _this.tableEdit();              
		        },
		        tableEdit: function(){
		        	table.on('tool(projectMaterialEvent)', function(obj){    //点击子目里的修改按钮
		        		var treeObj = $.fn.zTree.getZTreeObj("dataTree"), 
        					nodes = treeObj.getSelectedNodes();
	      				if(nodes.length>1 || !nodes.length || !nodes[0].id){
	      					layer.msg('请选择一条子目', {
                    			icon: 5,
							    btn: ['确定']
							});
	      					return;
	      				}
		              	var dataObj = obj.data;
		              	if(obj.event === 'edit'){
			                var openObj = {
			                  	"content": $(projectUnitYcaHtml).html(),
			                  	"title":'运材安修改',
			                  	"success": function(layero, index){
				                    layero.find("input[name='code']").val(dataObj.code).attr("readonly","readonly");
				                    layero.find("input[name='typeInfo']").val(dataObj.typeInfo);
				                    layero.find("input[name='content']").val(dataObj.content);
				                    layero.find("input[name='singleSumPrice']").val(dataObj.singleSumPrice);
				                    form.render(); 
				                    $('.addTableYcaDetails').hide();
				                    form.on('submit(projectUnitYcaFilter)', function(data){
				                      	var formData = data.field;
				                      	
			                      		layer.close(index);
			                      		return false;
			                    	});
			                  	},
			                    "yes": function(){
			                    	$('.projectUnitYcaFilter').trigger('click');                    	
			                    }
			                }
		                	layerOpenfn(openObj);
		              	}else if(obj.event === 'del'){ 
		              		var openObj = {
		                    	"content": '确认删除名称为'+dataObj.name+'的一行吗？',
		                    	"title":'删除',
		                    	"success": function(layero, index){		                      
		                    	},
		                    	"yes": function(layero, index){
		                      		$.ajaxRequest({
										url: interface.deletProjectDetail,
										data: {
											"cmd": 'edit',
											"unitProjectId": nodes[0].id,
											"unitProjectDetailId": dataObj.id
										},
										successfn: function(data) {
											if (data.success == true) {
												layer.msg("删除成功");
												obj.del();
											} else {
												layer.alert(data.msg);
											}
										},
										errorfn: function(data) {
											console.log(data);
										}
									})
		                        	layer.close(popIndex);		                        
		                    	}
		                  	}
		                  	layerOpenfn(openObj);
		              		
		              	} 
		            });
		        },
		        listEdit: function($obj){
	              var elem = $obj.elem,
	              $caozuo = $(elem).next('.layui-table-view');
	              if(!$caozuo.find('.caozuo-vis').length){
	                pathfn._toggleVisInit($obj.cols,$obj.elem,function(){
	                  form.render();
	                });
	              }else{
	                var inputArr = $caozuo.find('.caozuo-vis').find("input[type='checkbox']");
	                for(var i=0; i< inputArr.length; i++){
	                  var ischecked = inputArr.eq(i).prop('checked'),
	                    field = $(inputArr[i]).data('field');
	                  if(ischecked){                
	                    $caozuo.find('td[data-field="'+field+'"],th[data-field="'+field+'"]').hide(0);
	                  }else{
	                    $caozuo.find('td[data-field="'+field+'"],th[data-field="'+field+'"]').show(0);
	                  }
	                }
	              }
	            }
			};
          	bindEvents= function(){
          		$('.projectUnit').height('100%').find('.layui-tab-item').height(($('.projectUnit').height())-40-20);

      			$('.add-dataTree').click(function(){  //新增分部分项，根据编码添加
		    		var openObj = {
	                  	"content": $(projectUnitAddFbfxHtml).html(),
	                  	"title":'新增分部分项',
	                  	area: ['500px','80%'],
	                  	"success": function(layero, index){
	                  		var itemHtml = '',
	                  		unitproject = tableRender.unitproject;
							/*for(var i=2;i<unitproject.length;i++){
								itemHtml += '<div class="layui-form-item">'+
						            '<label class="layui-form-label">'+unitproject[i].text+(unitproject[i].isRequired === false ?  '&nbsp;' : '<span>*</span>')+'：</label>'+
						            '<div class="layui-input-block">'+
						               	'<input type="text" name="'+unitproject[i].name+'" lay-verify="'+(unitproject[i].isRequired === false ?  '' : 'required')+'|'+(!unitproject[i].filter ?  '' : unitproject[i].filter)+'" autocomplete="off" placeholder="请输入'+unitproject[i].text+'" class="layui-input">'+
						            '</div>'+
						        '</div>';
							}
	                  		$('.projectUnitItem').find('.projectUnitFilter').before(itemHtml);*/
	                  		form.render();
	                  		$('.addTableDetails').show(0);
	                    	form.on('submit(projectUnitFilter)', function(data){		                    		
	                    		var data = data.field;
	                    		$.ajaxRequest({
			                        url: interface.projectInsertItem,
			                        data: {
			                        	type: 'DING',
										dingId: backDataAll.id,
										bitProjectId: projectId,
										unitProjectId: '',
										times: 1,
										remark:''
			                        },
			                        successfn: function(data) {			                        	
			                        	if(!data.success){
			                        		layer.msg(data.msg, {
			                        			icon: 5,
										        btn: ['确定']
										    });
			                        	}else{
			                        		table.reload('item-table');
			                          		layer.close(popIndex);
			                        	}
			                          	
			                        },
			                        errorfn: function(data) {
			                          	table.reload('item-table');
			                        }
		                      	})	
		                      	return false;
	                    	})
	                  	},
	                    "yes": function(){
	                    	$('.projectUnitFilter').trigger('click');
	                    }
	                }
	                layerOpenfn(openObj); 
		    	})
      			$(document).on('click', '.addUnitDetails' , function(e){  //点击选择搜索按钮
      				require(['text!../pages/project/projectUnitQuery.html', './modules/project/projectUnitQuery'], function (projectUnitQueryHtml, projectUnitQuery){
						var openObj = {
							"content": projectUnitQueryHtml,
							"title": '查询',
							"area": ['96%','96%'],
							"btn": ['',''],
							"success": function(layero, index) {
								projectUnitQuery();
							},
							yes: function(index,layero){
		                    	if(!$('#dinge').is(":hidden")){
		                    		var checkStatus = table.checkStatus('classify-table');
		                    	}else{
		                    		var checkStatus = table.checkStatus('material-table');
		                    	}		                    	
	      						var data = checkStatus.data; 
	      						if(!data.length || data.length > 1){
	      							layer.msg('只能选择一条数据', {
	                        			icon: 5,
								        btn: ['确定']
								    });
	      						}else{
	      							backDataAll = data[0];
	      							$('.projectUnitItem').find('input[name="code"]').val(backDataAll['code']);
	      							layer.close(popIndex);
	      						}
		                    }
						}
						layerOpenfn(openObj);
					})
      			})
      			$('.add-projectMaterial').click(function(){      //点击运材安里面的新增按钮
      				var treeObj = $.fn.zTree.getZTreeObj("dataTree"), 
        					nodes = treeObj.getSelectedNodes();
	                var openObj = {
	                  	"content": $(projectUnitYcaHtml).html(),
	                  	"title":'新增运材安',
	                  	"success": function(layero, index){
	                  		$('.projectUnitYcaItem')[0].reset();
	                  		$('.addTableYcaDetails').show();
	                  		form.render();
	                    	form.on('submit(projectUnitYcaFilter)', function(data){
	                    		var data = data.field;
	                    		var postData = {
	                    			type: 'YCA',
	                    			classType: 'insert',
	                    			ycaId: backDataYcaAll.id,
									bitProjectId: projectId,
									unitProjectId: nodes[0].id,
									unitProjectDetailId: backDataYcaAll.id,
									times:1
	                    		}
		                      	$.ajaxRequest({
			                        url: interface.insertProjectDetail,
			                        data: postData,
			                        successfn: function(data) {
			                        	console.log(data);
			                        	debugger			                        	
			                        	if(!data.success){
			                        		layer.msg(data.msg, {
			                        			icon: 5,
										        btn: ['确定']
										    });
			                        	}else{
			                        		table.reload('projectMaterial-table');
			                          		layer.close(index);
			                        	}
			                          	
			                        },
			                        errorfn: function(data) {
			                          	table.reload('item-table');
			                        }
		                      	})
		                      	return false;
	                    	})
	                  	},
	                    "yes": function(){
	                    	$('.projectUnitYcaFilter').trigger('click');
	                    }
	                }
	                layerOpenfn(openObj);                 
	            })
	            $(document).on("click", ".addTableYcaDetails",function(){  //点击运材安里面的新增按钮 里面的选择搜索按钮
					var $this = $(this);
					var openObj = {
	                  	content: materialServiceHtml,
	                  	title:'运材安维护',
	                  	id:'materialServicePop',
	                  	area:  ['90%', '90%'],
	                  	success: function(layero, index){
	                  		materialService({id:'materialServicePop'});
	                  		return false;
	                  	},
	                    yes: function(index,layero){
	                    	var checkStatus = table.checkStatus('material-table')
      						,data = checkStatus.data; 
      						if(!data.length || data.length > 1){
      							layer.msg('只能选择一条数据', {
                        			icon: 5,
							        btn: ['确定']
							    });
      						}else{
      							data = data[0];
      							$('.projectUnitYcaItem').find('input[name="code"]').val(data.code); 
      							backDataYcaAll = data;
      							layer.close(popIndex);
      						}
	                    }
	                }
                	layerOpenfn(openObj);								
				});
          	}; 
          	form.verify({
			    decimal: function(value){
			    	var reg = /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/;
			    	if(!reg.test(value)){
			        	return '分值必须是非负数字';
			     	}
			    }
			}); 
			//监听Tab切换，以改变地址hash值
		  	element.on('tab(projectUnit)', function(data){
		    	var layId =  $(this).attr('lay-id');
		    	if(layId == 'ycahz'){
		    		require(['./modules/costService', 'text!../pages/dataBase/costService.html'], function (_projectDwJs, projectPopBackHtml){
		    			_projectDwJs({id:'projectYcaAll',bitProjectId:projectId});
		    		});	    		
		    	}else if(layId == 'fyhz'){
		    		require(['./modules/project/projectUnitCostAll'], function (_projectDwJs){
		    			_projectDwJs({id:'projectUnitCostAll',bitProjectId:projectId});
		    		});
		    	}
		  	});      	
          	layerOpenfn = function(openObj){
	            popIndex = layer.open({
	            	type: openObj.type || 1,
	                content: openObj.content || '',
	                title: openObj.title || '',
	                btn: ['确定','取消'],
	                area: openObj.area || '450px',
	                skin: 'lay-padding',
	                id: openObj.id || '',
	                scrollbar : true,
	                success: function(layero, index){
	                  	openObj.success(layero, index);
	                },
	                yes: function(index,layero){
	                  openObj.yes(index,layero);
	                },
	                btn2 : function(index, layero) {
					}
	            });
	        };
          	init();
        })
	}
	return projectDw;
})
